use POE;
use Time::Local;
my %timers = ();

my $tick = sub {
	my ($ctx, $key, $data) = @_;
	BotIrc::send_wisdom($ctx, "your $data->{type} is ready, enjoy!");
};

my $parse_ts = sub {
	my $ts = shift;
	my $delta = 0;
	if ($ts =~ s/^\@(\d{1,2}):(\d\d)(?::(\d\d))?(?:\+|$)//) {
		my $hr = $1;
		my $min = $2;
		my $sec = $3 // 0;
		my ($cursec, $curmin, $curhr, $curday, $curmon, $curyr) = localtime(time);
		my $ts = timelocal($sec, $min, $hr, $curday, $curmon, $curyr);
		$delta = $ts - time();
		$delta += 86400 if $delta <= 0;
	}
	while ($ts =~ s/^(\d+)([dhms]?)[,;]?//i) {
		my $val = $1;
		my $unit = lc($2);
		my $multiplier = 60;
		$multiplier = 1 if $unit eq 's';
		$multiplier = 3600 if $unit eq 'h';
		$multiplier = 86400 if $unit eq 'd';
		$delta += $val * $multiplier;
	}
	return if $ts ne '';
	return $delta;
};

my $format_ts = sub {
	my $delta = shift;
	my @res;
	if ($delta >= 86400) {
		my $days = int($delta / 86400);
		push @res, "$days days";
		$delta %= 86400;
	}
	if ($delta >= 3600) {
		my $hours = int($delta / 3600);
		push @res, "$hours hours";
		$delta %= 3600;
	}
	if ($delta >= 60) {
		my $minutes = int($delta / 60);
		push @res, "$minutes minutes";
		$delta %= 60;
	}
	if ($delta > 0) {
		my $seconds = int($delta);
		push @res, "$seconds seconds";
	}
	join(', ', @res);
};

{
	irc_commands => {
		pizza => sub {
			my ($source, $targets, $args, $auth) = @_;
			BotIrc::check_ctx() or return;

			my ($ts, $desc) = split(/\s+/, $args, 2);
			my $nick = BotIrc::ctx_source();
			$desc //= 'pizza';
			$desc =~ s/^\s+|\s+$//g;
			my $delta = $parse_ts->($ts);
			if (!$delta) {
				BotIrc::send_noise("invalid alarm time: $ts");
				return;
			}
			if ($delta > (86400 * 7)) {
				BotIrc::send_noise("for timers this long you shouldn't be relying on a puny bot like me...");
				return;
			}
			my $timerid = "pizza:$nick:$desc";

			BotIrc::ctx_set_addressee($nick);
			BotIrc::set_timer($timerid, $delta, $tick, {type => $desc});

			my $readable = $format_ts->($delta);
			BotIrc::send_wisdom("I'll let you know when your $desc is done, in $readable.");
		},
		unpizza => sub {
			my ($source, $targets, $args, $auth) = @_;
			BotIrc::check_ctx() or return;

			my $desc = $args;
			my $nick = BotIrc::ctx_source();
			$desc = 'pizza' if $desc =~ /^\s*$/;
			$desc =~ s/^\s+|\s+$//g;
			my $timerid = "pizza:$nick:$desc";

			if (BotIrc::clear_timer($timerid)) {
				BotIrc::send_noise("'$desc' timer cleared.");
			} else {
				BotIrc::send_noise("No '$desc' timer was active for you.");
			}
		},
	},
};
